#!/usr/bin/env python3
"""
Simple script to run the XML configuration directly without using GSM CLI
"""

import xml.etree.ElementTree as ET
import subprocess
import os
from pathlib import Path
import datetime

def run_xml_config(xml_file):
    """Run binary from XML configuration"""
    
    print(f"📋 Parsing XML configuration: {xml_file}")
    
    # Parse XML configuration
    tree = ET.parse(xml_file)
    root = tree.getroot()
    
    # Extract binary configuration
    binary_section = root.find('.//ParameterList[@name="Binary"]')
    if binary_section is None:
        print("❌ No Binary section found in XML")
        return False
    
    binary_path = None
    work_dir = None
    nproc = 1
    arguments = ""
    
    for param in binary_section.findall('Parameter'):
        param_name = param.get('name', '')
        param_value = param.get('value', '')
        
        if param_name == 'binary_path':
            binary_path = param_value
        elif param_name == 'work_dir':
            work_dir = param_value
        elif param_name == 'mpi_processes':
            nproc = int(param_value)
        elif param_name == 'arguments':
            arguments = param_value
    
    if not binary_path:
        print("❌ No binary_path specified in XML")
        return False
    
    # Extract logging configuration
    log_file = None
    logging_section = root.find('.//ParameterList[@name="Logging"]')
    if logging_section is not None:
        for param in logging_section.findall('Parameter'):
            if param.get('name') == 'log_file':
                log_file = param.get('value', '')
    
    # Process log file template
    if log_file and "$(date" in log_file:
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        log_file = log_file.replace("$(date +%Y%m%d_%H%M%S)", timestamp)
    
    print(f"🚀 Binary: {binary_path}")
    print(f"📁 Work directory: {work_dir}")
    print(f"📊 MPI processes: {nproc}")
    print(f"📄 Log file: {log_file}")
    print(f"🔧 Arguments: {arguments}")
    
    # Change to work directory if specified
    original_cwd = os.getcwd()
    if work_dir:
        work_dir_path = Path(work_dir)
        if not work_dir_path.exists():
            print(f"❌ Work directory not found: {work_dir_path}")
            return False
        os.chdir(work_dir_path)
        print(f"📁 Changed to work directory: {work_dir_path}")
    
    try:
        # Prepare command
        cmd = [binary_path]
        if arguments:
            cmd.extend(arguments.split())
        
        # Set up logging
        if log_file:
            log_path = Path(log_file)
            log_path.parent.mkdir(parents=True, exist_ok=True)
            
            print(f"📝 Running command: {' '.join(cmd)}")
            print(f"📄 Logging output to: {log_path}")
            
            with open(log_path, 'w') as f:
                result = subprocess.run(cmd, stdout=f, stderr=subprocess.STDOUT, text=True)
        else:
            print(f"📝 Running command: {' '.join(cmd)}")
            result = subprocess.run(cmd, text=True)
        
        print(f"📊 Exit code: {result.returncode}")
        
        if result.returncode == 0:
            print("✅ Execution completed successfully!")
            return True
        else:
            print(f"❌ Execution failed with exit code: {result.returncode}")
            return False
            
    except Exception as e:
        print(f"❌ Error running binary: {e}")
        return False
    
    finally:
        # Restore original working directory
        if work_dir:
            os.chdir(original_cwd)
            print(f"📁 Restored working directory: {original_cwd}")

if __name__ == "__main__":
    import sys
    
    if len(sys.argv) != 2:
        print("Usage: python run_xml_test.py <xml_file>")
        sys.exit(1)
    
    xml_file = sys.argv[1]
    success = run_xml_config(xml_file)
    sys.exit(0 if success else 1)